<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\madmin\service;

use app\index\model\MallBase;
use app\madmin\model\UserCash;
use app\madmin\model\Withdraw as admin;
use app\madmin\model\RechargeRecord;
use app\madmin\model\User;
use app\utils\SendMsg;
use app\utils\TrimData;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\model\Relation;
use WeChat\Exceptions\InvalidResponseException;
use WeChat\Exceptions\LocalCacheException;

class WithdrawService
{

    /**
     * 查询列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function findAll(array $data, int $page = 1, int $size = 10)
    {

        if (isset($data['nickname'])) {
            global $user;
            $admin = admin::withoutGlobalScope(['mallId'])->scope('userSearch', $data)
                ->where("uw.mall_id", $user->mall_id)
                ->field('uw.*,u.nickname');
        } else {
            $admin = admin::with(['userNickname']);
            $admin = TrimData::searchDataTrim($admin, $data, ['begin_date', 'end_date']);
            $admin = $admin->where($data);
        }
        $list = $admin->order('id', 'DESC')->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 读取一条数据
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(int $id)
    {
        $model = admin::with(['user'])->find($id);
        return [HTTP_SUCCESS, $model];
    }


    /**
     * 更新数据
     * @param int $id
     * @param array $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws Exception
     */
    public function update(int $id, array $data)
    {
        $update_time = $data['update_time'];
        unset($data['update_time']);
        $model = admin::where(['update_time' => $update_time])->lock(true)->find($id);

        if (!$model)
            throw new Exception("没有该记录", HTTP_NOTACCEPT);
        if ($model->getData("status") == $data['status'])
            throw new Exception("该操作无法执行", HTTP_NOTACCEPT);

        $user = User::where(['id' => $model->user_id])->with('wx')->find();

        if ($model->getData("status") == 0 && $data['status'] == 2) {
            $userCash = UserCash::where(['user_id' => $model->user_id])->lock(true)->find();
            $realityCash = bcadd((string)$model->withdraw, (string)$model->service_charge);
            $update = UserCash::where(['user_id' => $model->user_id])
                ->dec("withdraw", (float)$realityCash)
                ->inc("total", (float)$realityCash)
                ->update();

            if (empty($update))
                throw new \PDOException("取消失败");
            RechargeRecord::create(['user_id' => $user->id, 'mall_id' => $user->mall_id, 'base_in' => 'admin', 'source_type' => 2, 'source' => '提现被拒绝', 'is_online' => $model->is_online, 'type' => 0, 'card' => '{}', 'money' => $model->withdraw, 'service_charge' => '', 'remark' => '提现被拒绝', 'trade' => md5(uniqid() . rand(1000, 9999)), 'pay_no' => '', 'status' => 1, "old_cash" => $userCash->total,
                "new_cash" => bcadd((string)$userCash->total, $realityCash)]);
            $data['pay_no'] = null;
        } elseif ($model->getData("status") == 0 && !empty($model->is_online) && $data['status'] == 1) {
            switch ($user->wx->type) {
                case 2:
                    $baseIn = "wechat";
                    $method = "wx";
                    break;
                case 1:
                    $baseIn = "wechata";
                    $method = "wx";
                    break;
            }
            $paymentService = new PaymentService();
            $withdraw = (double)bcsub((string)$model->withdraw, (string)$model->service_charge);
            $arr = $paymentService->totalTransfers(
                $baseIn,
                $method,
                $user->wx->openid,
                $withdraw
            );
            if ($arr['result_code'] != "SUCCESS") {
                throw new Exception($arr['err_code_des'], HTTP_NOTACCEPT);
            }

            $data['pay_no'] = $arr["payment_no"];
            $data['pay_time'] = $arr["payment_time"];

            $msgData['mall_name'] = MallBase::getBase();
            $msgData['withdraw_cash'] = $withdraw;
            $msgData['withdraw_time'] = $model->create_time;

            //发送消息
            $user = User::with(['wx'])->find($model->user_id);
            switch ($user->wx->type) {
                case 1:
                    $url = "/pages/mine/balance/balance";
                    break;
                case 2:
                    $url = request()->domain() . "/h5/#/pages/mine/balance/balance";
                    break;
                default:
                    $url = request()->domain() . "/h5/#/pages/mine/balance/balance";
            }

            $sendMsg = new SendMsg("提现成功通知");
            try {
                $sendMsg->send($user, $msgData, $url);
            } catch (InvalidResponseException $e) {
            } catch (LocalCacheException $e) {
            } catch (Exception $e) {
            } catch (DataNotFoundException $e) {
            } catch (ModelNotFoundException $e) {
            } catch (DbException $e) {
            }

        } else {
            $data['pay_no'] = null;
        }

        $admin = admin::where('update_time', $update_time)
            ->where('id', $id)
            ->save($data);

        if (!$admin) {
            throw new Exception("更新失败", HTTP_NOTACCEPT);
        }

        RechargeRecord::update(
            [
                //'status' => $data['status'],
                'pay_no' => $data['pay_no']
            ],
            ['trade' => $model->serial_num]
        );

        return [HTTP_CREATED, $admin];
    }

    /**
     * @param $id
     * @return int
     */
    public function delete($id)
    {
        admin::destroy($id);
        return HTTP_NOCONTEND;
    }

}
